﻿package com.rragona.utils.coreXML 
{
	
	/**
	* ...
	* @author rragona
	* @version 1.0
	* 
	* This class is intended to take a url-style string (i.e. '/news/archive/2751/')
	* and path through a given XML object, using node attributes (@local) to 
	* return a specfic XML object. 
	* 
	*/
	
	public class XMLPathfinder 
	{
		
		public function XMLPathfinder() 
		{
			trace('XMLPathfinder is a static class and should not be instantiated.')
		}
		
		public static function loopURL(xml:XML, path:String):XML
		{
			var mA:Array = retPath(path);
			var retXML:XMLList = xml.*;
			
			for (var z:int = 0; z < mA.length; z++)
			{
				retXML = findMatch(retXML, mA[z])
			}
			return retXML.parent();
		}
		
		private static function findMatch(xml:XMLList, path:String):XMLList
		{
			var retList:XMLList = new XMLList();
			
			for (var z:int = 0; z < xml.length(); z++)
			{
				if (xml[z].@local == path)
				{
					retList = xml[z].*;
					break;
				}
			}
			return retList;
		}
		
		public static function retPath(path:String):Array
		{
			var rArray:Array = new Array();
			var cleanPath:String = formatCheck(path);
			var fP_A:Array = cleanPath.split('/');
		   
			for (var z:int = 1; z < fP_A.length - 1; z++)
			{
				rArray.push(fP_A[z]);
			}
			return rArray;
		}
		
		private static function formatCheck(path:String):String 
		{
			var retS:String = path;
			var lastC:String = path.substring(path.length - 1, path.length);
			
			if(lastC != "/")
			{
				retS += "/";
			}
			return retS;
		}
	}
	
}